<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { storeToRefs } from 'pinia';
import TnAvatar from '@tuniao/tnui-vue3-uniapp/components/avatar/src/avatar.vue'
import TnListItem from '@tuniao/tnui-vue3-uniapp/components/list/src/list-item.vue'
import TnButton from '@tuniao/tnui-vue3-uniapp/components/button/src/button.vue'
import TnInput from '@tuniao/tnui-vue3-uniapp/components/input/src/input.vue'
import TnSubsection from '@tuniao/tnui-vue3-uniapp/components/subsection/src/subsection.vue'
import TnSubsectionItem from '@tuniao/tnui-vue3-uniapp/components/subsection/src/subsection-item.vue'
import CustomPopup from '@/components/CustomPopup/index.vue'
import { useUserStore } from '@/store/user'
import { useModelStore } from '@/store/model';
import api from '@/api'
import type { ModelVo } from '@/types'
import avatarFile from '@/static/images/avatar.png'
import Message from '@/utils/message'
import { compressImage } from '@/utils/image'

const userStore = useUserStore()
const modelStore = useModelStore()

const updateUserRef = ref()

const { userInfo, avatarPath } = storeToRefs(userStore);
const { textModel, imageModel } = storeToRefs(modelStore);

const imageUrl = ref()

const updateUser = ref({
    showUpdateUser: false,
    type: 1,
    title: '',
    subTitle: '',
    nickName: '',
    avatar: '',
    email: '',
    phonenumber: '',
})

const updatePassword = ref({
    showUpdatePassword: false,
    oldPassword: '',
    newPassword: '',
})

const changeModel = ref<{
    showChangeModel: boolean,
    type: number,
    modelList: ModelVo[],
    model: string
}>({
    showChangeModel: false,
    type: 0,
    modelList: [],
    model: textModel.value
})

const updateUserInfo = (type: number) => {
    updateUser.value.type = type
    if (type === 1) {
        updateUser.value.title = '修改头像'
        updateUser.value.avatar = ''
    } else if (type === 2) {
        updateUser.value.title = '修改信息'
        updateUser.value.nickName = userInfo.value.nickName
        updateUser.value.email = userInfo.value.email
        updateUser.value.phonenumber = userInfo.value.phonenumber
    }
    updateUser.value.showUpdateUser = true
}

const chooseAvatar = () => {
    uni.chooseImage({
        count: 1,
        success: async (res) => {
            const filePath = res.tempFilePaths[0]
            const tempPath = await compressImage(filePath, 50)
            imageUrl.value = tempPath
        },
        fail: (err) => {
            console.log(err);
        }
    })
}

const onCancel = () => {
    imageUrl.value = ''
}

const onConfirm = async (res: any) => {
    updateUser.value.avatar = res.tempFilePath
    const result = await api.user.updateAvatar(res.tempFilePath)
    imageUrl.value = ''
    if (result.code === 200) {
        userInfo.value.avatar = result.data.imgUrl
        updateUser.value.showUpdateUser = false
        userStore.getUserInfo()
        Message.success('修改成功')
    } else {
        updateUser.value.avatar = ''
    }
}

const handleChangeModel = () => {
    changeModel.value.showChangeModel = true
    listModel()
}

const handleUpdatePwd = () => {
    updatePassword.value.showUpdatePassword = true
    updatePassword.value.oldPassword = ''
    updatePassword.value.newPassword = ''
}

const listModel = async () => {
    const index = changeModel.value.type
    const type = index === 0 ? 'text' : 'image'
    let model = index === 0 ? textModel.value : imageModel.value
    const res = await api.model.listModel(type)
    changeModel.value.modelList = res.data
    if (model === '') {
        model = res.data[0].value
    }
    switchModel(model)
}

const switchModel = (model: string) => {
    changeModel.value.model = model;
    if (changeModel.value.type === 0) {
        textModel.value = model
    } else {
        imageModel.value = model
    }
}

const handleUpdateUser = async () => {
    const res = await api.user.updateProfile({
        userId: userInfo.value.userId,
        nickName: updateUser.value.nickName,
        email: updateUser.value.email,
        phonenumber: updateUser.value.phonenumber
    })
    if (res.code === 200) {
        userStore.getUserInfo()
        updateUser.value.showUpdateUser = false
        Message.success('修改成功')
    }
}

const handleUpdatePassword = async () => {
    const res = await api.user.updatePassword({
        oldPassword: updatePassword.value.oldPassword,
        newPassword: updatePassword.value.newPassword
    })
    if (res.code === 200) {
        updatePassword.value.showUpdatePassword = false
        Message.success('修改成功')
    }
}

const logout = () => {
    userStore.logout()
}

onMounted(() => {

})
</script>
<template>

    <view class="tn-w-full">
        <view class="tn-w-full tn-blue_bg">
            <view class="tn-w-full tn-h-50"></view>
            <view class="tn-flex tn-flex-row justify-between tn-p">
                <view class="tn-flex-center-center avatar-container">
                    <TnAvatar @click="updateUserInfo(1)" size="200rpx" :url="avatarPath ? avatarPath : avatarFile" />
                    <view class="edit-icon">
                        <TnIcon name="edit" size="34rpx" color="#fff" />
                    </view>
                </view>
                <view @click="updateUserInfo(2)" class="tn-flex tn-flex-grow tn-pl-sm">
                    <view class="tn-flex tn-flex-grow tn-flex-column tn-p-xs">
                        <view class="tn-text-2xl tn-text-bold">{{ userInfo.nickName }}</view>
                        <view class="tn-text tn-mt-sm">{{ userInfo.email }}</view>
                    </view>
                    <view class="tn-flex-center-right">
                        <TnIcon name="right" size="40rpx" color="#fff" />
                    </view>
                </view>
            </view>
        </view>
        <view>
            <TnListItem bottom-border>用户名：{{ userInfo.userName }}</TnListItem>
            <TnListItem bottom-border>邮箱：{{ userInfo.email }}</TnListItem>
            <TnListItem bottom-border>昵称：{{ userInfo.nickName }}</TnListItem>
            <TnListItem>手机号码：{{ userInfo.phonenumber }}</TnListItem>
        </view>
        <view class="tn-h-10 tn-gray-disabled_bg tn-w-full"></view>
        <view>
            <TnListItem @click="handleChangeModel" right-icon="right" bottom-border>切换模型</TnListItem>
            <TnListItem @click="handleUpdatePwd" right-icon="right" bottom-border>修改密码</TnListItem>
        </view>
        <view class="tn-h-10 tn-gray-disabled_bg tn-w-full"></view>
        <view class="tn-text-center tn-mt-xl">
            <TnButton @click="logout" width="90%" shape="round" size="xl">退出登录</TnButton>
        </view>

    </view>

    <CustomPopup ref="updateUserRef" v-model="updateUser.showUpdateUser" :title="updateUser.title">
        <view v-if="updateUser.type === 1" class="tn-flex-start-center tn-mt-lg tn-mb-lg">
            <TnAvatar v-if="updateUser.avatar" @click="chooseAvatar" size="300rpx" :url="updateUser.avatar" />
            <TnAvatar v-else icon="image" @click="chooseAvatar" border size="300rpx" />
        </view>
        <template v-if="updateUser.type === 2">
            <view class="tn-mt-lg tn-mb-lg">
                <TnInput v-model="updateUser.nickName" placeholder="请输入用户昵称" />
            </view>
            <view class="tn-mb-lg">
                <TnInput v-model="updateUser.email" placeholder="请输入邮箱" />
            </view>
            <view class="tn-mb-lg">
                <TnInput v-model="updateUser.phonenumber" placeholder="请输入手机号码" />
            </view>
            <view>
                <TnButton @click="handleUpdateUser" width="100%" size="xl">保存</TnButton>
            </view>
        </template>
    </CustomPopup>

    <t-cropper mode="ratio" :imageUrl="imageUrl" :width="500" :height="500" :radius="100" :delay="150"
        @cancel="onCancel" @confirm="onConfirm"></t-cropper>

    <CustomPopup v-model="changeModel.showChangeModel" title="切换模型">
        <view class="tn-mt-xl">
            <TnSubsection @change="listModel" v-model="changeModel.type">
                <TnSubsectionItem title="文本" />
                <TnSubsectionItem title="画图" />
            </TnSubsection>
        </view>
        <scroll-view class="tn-mt-xl" scroll-y>
            <TnListItem v-for="(modelVo, index) in changeModel.modelList"
                :bg-color="modelVo.value === changeModel.model ? 'tn-type-primary' : ''"
                @click="switchModel(modelVo.value)" :key="'model-' + index" bottom-border>
                {{ modelVo.name }}
            </TnListItem>
        </scroll-view>
    </CustomPopup>

    <CustomPopup ref="updatePasswordRef" v-model="updatePassword.showUpdatePassword" title="修改密码">
        <view class="tn-mt-lg tn-mb-lg">
            <TnInput v-model="updatePassword.oldPassword" placeholder="请输入旧密码" />
        </view>
        <view class="tn-mb-lg">
            <TnInput v-model="updatePassword.newPassword" placeholder="请输入新密码" />
        </view>
        <view>
            <TnButton @click="handleUpdatePassword" width="100%" size="xl">保存</TnButton>
        </view>
    </CustomPopup>
</template>
<style lang="scss" scoped>
.avatar-container {
    position: relative;
    display: inline-block;
    /* 确保容器大小与头像大小一致 */
}

.edit-icon {
    position: absolute;
    bottom: 4rpx;
    /* 调整到底部 */
    left: 50%;
    /* 水平居中 */
    transform: translateX(-50%);
    /* 水平居中 */
    background-color: rgba(0, 0, 0, 0.5);
    /* 可选：添加背景色以提高可见性 */
    border-radius: 50%;
    /* 可选：使背景色圆形 */
    padding: 4rpx;
    /* 可选：添加一些内边距 */
}
</style>